﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace ObjectToXmlSerializationBasic
{
    public class Contacts
    {
        public IList<Customer> Customers = new List<Customer>();
        public IList<Supplier> Suppliers = new List<Supplier>();
        public void ReadXml(XmlReader r)
        {
            bool isEmpty = r.IsEmptyElement; // This ensures we don't get
            r.ReadStartElement(); // snookered by an empty
            if (isEmpty) return; // <contacts/> element!
            while (r.NodeType == XmlNodeType.Element)
            {
                if (r.Name == Customer.XmlName) Customers.Add(new Customer(r));
                else if (r.Name == Supplier.XmlName) Suppliers.Add(new Supplier(r));
                else
                    throw new XmlException("Unexpected node: " + r.Name);
            }
            r.ReadEndElement();
        }
        public void WriteXml(XmlWriter w)
        {
            foreach (Customer c in Customers)
            {
                w.WriteStartElement(Customer.XmlName);
                c.WriteXml(w);
                w.WriteEndElement();
            }
            foreach (Supplier s in Suppliers)
            {
                w.WriteStartElement(Supplier.XmlName);
                s.WriteXml(w);
                w.WriteEndElement();
            }
        }
    }
}
